import {addAddress, delAddress, getAddress, updateAddress} from '@/api/address'
import {
  addGoodToOnlineCart,
  delGoodsInOnlineCart,
  getOnlineCart,
  mergeLocalCart,
  updateGoodsInOnlineCart
} from '@/api/cart'
import {useUserStore} from '@/stores/user'
import type {Address, CartItem, CartState} from '@/types/cart'
import {defineStore} from 'pinia'


let userStore = useUserStore()

export const useCartStore = defineStore({
  id: 'cart',
  state: () => ({
    list: [],
    // 收货地址
    address: []
  } as CartState),
  getters: {
    // 购物车有效且商品的总数量
    allLength(): number {
      let l = 0
      this.list.forEach(i => {
        if (i.isEffective) l += i.count
      })
      return l
    },
    // 购物车有效且已选中商品的总数量
    length(): number {
      let l = 0
      this.list.forEach(i => {
        if (i.selected && i.isEffective) l += i.count
      })
      return l
    },
    // 已选择且有效的商品列表
    esList(): CartItem[] {
      return this.list.filter(i => i.selected && i.isEffective)
    },
    // 有效商品列表
    eList(): CartItem[] {
      return this.list.filter(i => i.isEffective)
    },
    // 无效商品列表
    unEList(): CartItem[] {
      return this.list.filter(i => !i.isEffective)
    },
    // 已选择且有效商品的总价
    totalPrice(): number {
      let s = 0
      this.list.forEach(i => {
        if (i.selected && i.isEffective) s += i.count * +(i?.price || 0)
      })
      return s
    },

    // 默认收货地址
    defaultAddress(): Address | undefined {
      return this.address.find(item => item.isDefault === 1)
    }
  },
  actions: {
    // 初始化购物车
    async initCart(): Promise<boolean> {
      // 未登录则不做处理
      if (!userStore.userInfo.token) return false

      // 已登录 更新本地购物车到线上
      let res: any = await mergeLocalCart(this.list)
      if (res?.code) return false

      // 更新线上购物车到本地
      res = await getOnlineCart()
      if (res?.result?.length === undefined) return false
      this.list = <CartItem[]>res.result
      return true
    },

    // 添加商品到购物车
    addInCart(good: CartItem): Promise<boolean> {
      return new Promise<boolean>(async (resolve) => {
        if (userStore.userInfo.token) {
          // 已登录则调用接口更新线上购物车
          let res: any = await addGoodToOnlineCart(good.skuId ?? '', good.count)
          if (res.code) return resolve(false)
        }
        // 线上购物车更新成功（或未登录），更新本地购物车
        let index = this.list.findIndex(item => item.skuId === good.skuId)
        if (index !== -1) {
          good.count += this.list[index].count
          this.list.splice(index, 1)
        }
        this.list.unshift(good)
        resolve(true)
      })
    },

    // 删除商品
    deleteFromCart(good: CartItem): Promise<boolean> {
      return new Promise<boolean>(async (resolve) => {
        if (userStore.userInfo.token) {
          // 已登录，删除线上购物车对应商品
          let res: any = await delGoodsInOnlineCart([good.skuId ?? ''])
          if (res.code) return resolve(false)
        }
        // 线上购物车删除成功（或未登录），删除本地购物车对应商品
        let index = this.list.findIndex(item => item.skuId === good.skuId)
        if (index !== -1) {
          this.list.splice(index, 1)
          resolve(true)
        } else resolve(false)
      })
    },
    // 删除已选中商品
    async deleteESListAll(): Promise<boolean> {
      let flag = true
      for (const item of this.esList) {
        let res = await this.deleteFromCart(item)
        if (!res) flag = false
      }
      return flag
    },
    // 删除无效商品
    async deleteUnEListAll(): Promise<boolean> {
      let flag = true
      for (const item of this.unEList) {
        let res = await this.deleteFromCart(item)
        if (!res) flag = false
      }
      return flag
    },

    // 更新商品
    updateFromCart(oldSkuId: string, good: CartItem): Promise<boolean> {
      return new Promise<boolean>(async (resolve) => {
        if (!oldSkuId) return resolve(false)
        if (userStore.userInfo.token) {
          let res: any
          // 如果新旧相同，说明未改变sku
          if (oldSkuId === good.skuId) {
            // 更新线上购物车商品信息
            res = await updateGoodsInOnlineCart(oldSkuId, good)
            if (res?.code) return resolve(false)
          } else {
            console.log('商品sku改变')
          }
        }
        // 线上购物车更新成功（或未登录），更新本地购物车
        let index = this.list.findIndex(item => item.skuId === oldSkuId)
        if (index !== -1) {
          // 覆盖旧商品内容
          this.list[index] = {
            ...this.list[index],
            ...good
          }
          resolve(true)
        } else resolve(false)
      })
    },

    // 更新所有有效商品到线上购物车
    updateAll(): Promise<any> {
      let reqList = []
      for (const eListElement of this.eList) {
        reqList.push(this.updateFromCart(eListElement.skuId ?? '', eListElement))
      }
      return Promise.all(reqList)
    },

    // 新增收货地址
    async addAddress(addr: Address): Promise<boolean> {
      let res = await addAddress(addr)
      if (res.code) return false
      res = await getAddress()
      this.address = res.result.reverse() ?? this.address
      return true
    },
    // 更新收货地址
    async updateAddress(addr: Address, frash: boolean = true): Promise<boolean> {
      let res = await updateAddress(addr)
      if (res.code) return false
      if(!frash) return true
      res = await getAddress()
      this.address = res.result.reverse() ?? this.address
      return true
    },
    // 删除收货地址
    async delAddress(addr: Address): Promise<boolean> {
      let res = await delAddress(addr)
      if (res.code) return false
      res = await getAddress()
      this.address = res.result.reverse() ?? this.address
      return true
    }
  },
  persist: {
    enabled: true,
    strategies: [{storage: localStorage}]
  }
})